/**
 * 
 */
package com.td.framework.webmanager.common;

import java.util.Stack;

import com.td.framework.webmanager.domain.AppsysQxygns;

/**
 * 
 * Title:生成权限树 Description:实现生成权限树所需XML方法 
 * Copyright: Copyright (c) 2008 Company
 * 北京水软科技有限公司
 * 
 * @author FLT006
 * @version 1.0
 */
public class TreeCreateHandler {
	private Stack stack = null;
	private StringBuffer strbuffer = null;
	public TreeCreateHandler()
	{
		strbuffer = new StringBuffer();
	}
    /**
     * 开始解析
     * @throws java.lang.Exception
     */
    public void startDocument() throws Exception{
        stack = new Stack();
    }
    
    /**
     * 解析前
     * @param bean
     * @throws java.lang.Exception
     */
    public void startElement(AppsysQxygns bean) throws Exception{
        if(stack.empty()){
            return;
        }
        AppsysQxygns treebean = (AppsysQxygns)bean;
        String sjbh = treebean.getSjbh();//上级编号
        boolean flag = true;
        do{
        	AppsysQxygns tmp_bean = (AppsysQxygns)stack.peek();
           String ymbh = tmp_bean.getYmbh();//页面编号
           if(!sjbh.equals(ymbh)){
               strbuffer.append("</item >\n");
               stack.pop();
           }
           else{
               flag = false;
           }
        }while(flag && !stack.empty());
    }

    /**
     * 解析后
     * @param bean
     * @throws java.lang.Exception
     */
    public void endElement(AppsysQxygns bean) throws Exception{
    	AppsysQxygns treebean = (AppsysQxygns)bean;
        String link = "";
        if(treebean.getSbsjd()==0){
            stack.push(treebean);
            strbuffer.append("<item pk=\"" + treebean.getYmbh() +
                             "\" name=\"" + treebean.getYmmc() + "\" link=\""+link+"\">\n");
        }
        else{
            strbuffer.append("     <item pk=\"" + treebean.getYmbh() +
                             "\" name=\"" + treebean.getYmmc() + "\" link=\""+link+"\"></item>\n");
        }
    }

    /**
     * 结束解析
     * @throws java.lang.Exception
     */
    public void endDocument() throws Exception{
        while(!stack.empty()){
            strbuffer.append("</item>\n");
            stack.pop();
        }
    }
    
    /**
     * 取Xml结果
     * @return
     */
    public StringBuffer getResult(String xmlName){
        StringBuffer tmp_buffer = new StringBuffer();
        tmp_buffer.append("<XML ID=\""+xmlName+"XML\">\n");
        tmp_buffer.append("<item pk=\"root\" name=\"\" link=\"\">\n");
        if(strbuffer!=null){
          tmp_buffer.append(strbuffer.toString());
        }
        tmp_buffer.append("</item>\n");
        tmp_buffer.append("</XML>");

        return tmp_buffer;
    }
}
